<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 1/4/2015
 * Time: 6:02 PM
 */
namespace BC\Wallet\Bitcoin;

use BC\SiteIndex;
use BC\User\Session\UserSession;
use CPath\Build\IBuildable;
use CPath\Build\IBuildRequest;
use CPath\Render\HTML\Element\Form\HTMLForm;
use CPath\Render\HTML\Element\Form\HTMLInputField;
use CPath\Render\HTML\Element\Form\HTMLSubmit;
use CPath\Render\HTML\Element\HTMLElement;
use CPath\Render\HTML\Header\HTMLMetaTag;
use CPath\Request\Executable\IExecutable;
use CPath\Request\Form\IFormRequest;
use CPath\Request\IRequest;
use CPath\Request\Validation\RequiredValidation;
use CPath\Response\Common\RedirectResponse;
use CPath\Response\IResponse;
use CPath\Route\IRoutable;
use CPath\Route\RouteBuilder;

class BitcoinWalletCreate implements IExecutable, IRoutable, IBuildable
{
	const PARAM_NAME = 'name';
	const PARAM_CREATE = 'create';
	const FORM_PATH = '/wallets/create';
	const FORM_METHOD = 'POST';
	const PARAM_OWNER_ID = 'owner_id';

	/**
	 * Execute a command and return a response. Does not render
	 * @param IRequest $Request
	 * @return IResponse the execution response
	 */
	function execute(IRequest $Request) {
		$UserSession = UserSession::fromSession($Request);
		$userFingerprints = $UserSession->getUserFingerprints();

		$Wallets = BitcoinWallet::search($userFingerprints);
		$walletNames = array();
		foreach($Wallets as $Wallet)
			$walletNames[] = $Wallet->getPGPInfo($Request)->getUserID();

		$defaultName = "MyWallet";
		for($i=1;; $i++) {
			if(!in_array($defaultName, $walletNames))
				break;
			$defaultName = "Wallet-" . $i;
		}

		$Form = new HTMLForm(self::FORM_METHOD, self::FORM_PATH, 'form-wallets',
			new HTMLMetaTag(HTMLMetaTag::META_TITLE, 'User Wallets'),
//			new HTMLHeaderScript(__DIR__ . '\assets\form-wallet-create.js'),

			new HTMLElement('fieldset',
				new HTMLElement('legend', 'legend-create', 'Create a new Bitcoin Wallet'),

				"Owner's public key fingerprint(s) <br/>",
				new HTMLInputField(self::PARAM_OWNER_ID, implode(', ', $userFingerprints),
					new RequiredValidation()
				),

				"<br/><br/>Wallet Name<br/>",
				new HTMLInputField(self::PARAM_NAME, $defaultName,
					new RequiredValidation()
				),

				new HTMLSubmit('create', 'Create')
			)
		);

		if (!$Request instanceof IFormRequest)
			return $Form;

		$name               = $Form->validateField($Request, self::PARAM_NAME);
		$userFingerprints   = $Form->validateField($Request, self::PARAM_OWNER_ID);
		$userFingerprints   = array_filter(preg_split('/\s*,\s*/', $userFingerprints));
		$Wallet = BitcoinWallet::create($Request, $userFingerprints, $name); // Choose identity(s)

		return new RedirectResponse(BitcoinWallet::getRequestPath($Wallet->getGrantFingerprint()), "Wallet created successfully", 5);
	}

	// Static

	/**
	 * Route the request to this class object and return the object
	 * @param IRequest $Request the IRequest inst for this render
	 * @param array|null $Previous all previous response object that were passed from a handler, if any
	 * @param null|mixed $_arg [varargs] passed by route map
	 * @return void|bool|Object returns a response object
	 * If nothing is returned (or bool[true]), it is assumed that rendering has occurred and the request ends
	 * If false is returned, this static handler will be called again if another handler returns an object
	 * If an object is returned, it is passed along to the next handler
	 */
	static function routeRequestStatic(IRequest $Request, Array &$Previous = array(), $_arg = null) {
		return new BitcoinWalletCreate();
	}

	/**
	 * Handle this request and render any content
	 * @param IBuildRequest $Request the build request inst for this build session
	 * @return void
	 * @build --disable 0
	 * Note: Use doctag 'build' with '--disable 1' to have this IBuildable class skipped during a build
	 */
	static function handleBuildStatic(IBuildRequest $Request) {
		$Builder = new RouteBuilder($Request, new SiteIndex());
		$Builder->writeRoute(self::FORM_METHOD . ' ' . self::FORM_PATH, __CLASS__);
	}
}